<?php
/**
 * Created by PhpStorm.
 * User: qianweiliang
 * Date: 2018/4/9
 * Time: 下午10:49
 */

namespace App\Utils;

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

/**
 * 上传到七牛公共类及方法
 * Class UploadToQiniu
 * @package App\Utils
 */
class UploadToQiniu
{

    private $accessKey;
    private $secretKey;
    private $bucket;
    private $token;
    private $key;
    private $auth;
    private $domain;
    
    // 文件下载的目录
    const DOWNLOAD_FILE_PATH = 'qiniu/video/';
    
    private $file_name;
    private $file_extension;

    function __construct($qiniu_config)
    {
        $this->accessKey = $qiniu_config['accessKey'];
        $this->secretKey = $qiniu_config['secretKey'];
        $this->bucket = $qiniu_config['bucket'];
        $this->domain = $qiniu_config['domain'];

        $this->auth = new Auth($this->accessKey, $this->secretKey);
    }

    /**
     * 定义七牛的token和key
     */
    private function getToken(){
        $source_prefix = $this->bucket == 'factsource' ? 'source1' : $this->bucket == 'reportsource' ? 'source2' : 'source3';

        $this->token = $this->auth->uploadToken($this->bucket);
        $this->key = date('Ymd',time()) . "/" . $source_prefix . substr(md5(time() . mt_rand(1000,9999)), 0, 20);
    }
    
    public function token()
    {
        return [$this->token, $this->key . '.mp4'];
    }
    
    
    /**
     * 文件下载到本地
     *
     * @param $file_url
     *
     * @return array
     */
    public function download($file_url)
    {
        $in = fopen($file_url, 'rb');
        $out = fopen($this->file_name, 'wb');
    
        while ($chunk = fread($in,8192))
        {
            fwrite($out, $chunk, 8192);
        }
        fclose($in);
        fclose($out);
        
        if (file_exists($this->file_name)){
            
            return ['status' => true, 'path' => $this->file_name];
        }else {
            
            return ['status' => false, 'msg' => '视频保存到本地失败'];
        }
    }
    
    public function putFile($path)
    {
        $this->getToken();
        
        $uploadMgr = new UploadManager();
    
        list($ret, $err) = $uploadMgr->putFile($this->token, $this->key . '.mp4', $path);
        
        if ($err !== null) {
            
            return $ret;
        }
        
        return $err;
    }
    
    public function ttt($file_url)
    {
        // 先获取文件名称和文件后缀
        $file_arr = explode('/', explode('?', $file_url)[0]);
        $file_extensions = explode('.', $file_arr[count($file_arr) - 1]);
    
        $this->file_extension = '.' . $file_extensions[count($file_extensions) - 1];
        $this->file_name = self::DOWNLOAD_FILE_PATH . $file_arr[count($file_arr) - 1];
    
        // 获取七牛token和key
        $this->getToken();
    
        $bucketManager = new BucketManager($this->auth);
    
        list($ret, $err) = $bucketManager->fetch($file_url, $this->bucket, $this->key . '.mp4');
        
        return ($err === null) ? $err : $ret;
    }
    
    /**
     * 将url转存到七牛
     *
     * @param $file_url
     *
     * @return array
     */
    public function fetch($file_url)
    {
        // 先获取文件名称和文件后缀
        $file_arr = $file_arr = explode('/', explode('?', $file_url)[0]);
        $file_extensions = explode('.', $file_arr[count($file_arr) - 1]);
        
        $this->file_extension = '.' . $file_extensions[count($file_extensions) - 1];
        $this->file_name = self::DOWNLOAD_FILE_PATH . $file_arr[count($file_arr) - 1];
    
        // 获取七牛token和key
        $this->getToken();

        $bucketManager = new BucketManager($this->auth);

        list($ret, $err) = $bucketManager->fetch($file_url, $this->bucket, $this->key . $this->file_extension);
        
        if ($err !== null) {
            // 将错误信息写入到文件中，方便查看
            file_put_contents('qiniu/upload_to_qiniu_fetch_error.log', date('Y-m-d H:i:s') . ';file_url:' . $file_url . ';error_msg:' . serialize($err) . "\r\n", FILE_APPEND);
            // 转存失败，保存到本地再上传
            $video_result = $this->download($file_url);

            if ($video_result['status']){
                // 上传到七牛
                $uploadMgr = new UploadManager();
    
                list($ret2, $err2) = $uploadMgr->putFile($this->token, $this->key . $this->file_extension, $video_result['path']);
                
                if ($err2 !== null) {
                    file_put_contents('qiniu/upload_to_qiniu_upload_error.log', date('Y-m-d H:i:s') . ';file_name:' . $video_result['path'] . ';error_msg:' . serialize($err2) . "\r\n", FILE_APPEND);
                    // 再次上传错误
                    return ['status' => false, 'msg' => '上传文件失败'];
                    
                }else {
                    // 保存成功，删除本地文件
                    unlink($this->file_name);
                    
                    return ['status' => true, 'key' => $this->domain . $ret2['key']];
                }
            }else {
                
                return ['status' => false, 'msg' => $video_result['msg']];
            }
            
        } else {
            
            return ['status' => true, 'key' => $this->domain . $ret['key']];
        }
    }
}